public class O36 {
    Node head,pre;
    public Node treeToDoublyList(Node root) {
        if (root==null)
            return null;
        head = new Node();
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }
    void dfs(Node node){
        if (node==null)
            return;
        dfs(node.left);
        if (pre == null){
            head = node;
        }else {
            pre.right = node;
        }
        node.left = pre;
        pre = node;
        dfs(node.right);
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    Node next;
    Node random;
    public Node() {}

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};